package com.liangzi.service_core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liangzi.liangzi_common.result.R;
import com.liangzi.service_core.pojo.bo.SnowflakeManager;
import com.liangzi.service_core.pojo.entity.VisitMedicalCard;
import com.liangzi.service_core.mapper.VisitMedicalCardMapper;
import com.liangzi.service_core.pojo.vo.VisitMedicalCardVO;
import com.liangzi.service_core.service.VisitMedicalCardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 就诊卡表 服务实现类
 * </p>
 *
 * @author zhj
 * @since 2021-12-17
 */
@Service
@Slf4j
public class VisitMedicalCardServiceImpl extends ServiceImpl<VisitMedicalCardMapper, VisitMedicalCard> implements VisitMedicalCardService {


    @Autowired
    private VisitMedicalCardMapper visitMedicalCardMapper;
    @Autowired
    private SnowflakeManager snowflakeManager;


    @Override
    public String medicalCardExistByUserId(String userId) {
        // 判断是否有就诊卡
        QueryWrapper<VisitMedicalCard> visitMedicalCardQueryWrapper = new QueryWrapper<>();
        visitMedicalCardQueryWrapper.eq("user_id",userId);
        VisitMedicalCard one = visitMedicalCardMapper.selectOne(visitMedicalCardQueryWrapper);
        return one == null?null:one.getMedicalCardId();
    }

    @Override
    public String saveCard(String userId, VisitMedicalCardVO visitMedicalCardVO) {
        // 判断是否有卡
        QueryWrapper<VisitMedicalCard> visitMedicalCardQueryWrapper = new QueryWrapper<>();
        visitMedicalCardQueryWrapper.eq("user_id",userId);
        VisitMedicalCard haveVisitMedicalCard = visitMedicalCardMapper.selectOne(visitMedicalCardQueryWrapper);
        if(haveVisitMedicalCard != null){
            log.info(userId+ "   已有卡，不能再次开卡");
            return null;
        }
        // 进行绑卡操作
        VisitMedicalCard visitMedicalCard = new VisitMedicalCard();
        BeanUtils.copyProperties(visitMedicalCardVO,visitMedicalCard,VisitMedicalCard.class);
        visitMedicalCard.setUserId(userId);
        visitMedicalCard.setMedicalCardId(visitMedicalCardVO.getMedicalCardId());
        Long cardId = null;
        try {
            cardId  = snowflakeManager.nextValue();
            visitMedicalCard.setMedicalCardId(cardId.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(visitMedicalCardMapper.insert(visitMedicalCard)>0 ){
            return cardId.toString();
        };
        return null;
    }
}
